import {defineStore} from 'pinia'
import {reqLogin} from '@/api/user'
import type {LoginRequestData} from '@/api/types/user'
import {computed, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'

// 用户信息接口
interface UserState {
    token: string
    username: string
    isHr: boolean
}

// 本地存储key常量
const STORAGE_KEY = {
    TOKEN: 'token',
    USERNAME: 'username'
} as const

export const useUserStore = defineStore('user', () => {
    // 状态定义
    const token = ref<string>(localStorage.getItem(STORAGE_KEY.TOKEN) || '')
    const username = ref<string>(localStorage.getItem(STORAGE_KEY.USERNAME) || '')
    const isHr = ref<boolean>()
    const router = useRouter()

    // 保存用户信息到本地存储
    const saveUserToStorage = (userInfo: Partial<UserState>) => {
        if (userInfo.token) {
            localStorage.setItem(STORAGE_KEY.TOKEN, userInfo.token)
        }
        if (userInfo.username) {
            localStorage.setItem(STORAGE_KEY.USERNAME, userInfo.username)
        }
    }

    // 清除本地存储的用户信息
    const clearUserFromStorage = () => {
        localStorage.removeItem(STORAGE_KEY.TOKEN)
        localStorage.removeItem(STORAGE_KEY.USERNAME)
    }

    // 更新用户状态
    const updateUserState = (userInfo: Partial<UserState>) => {
        if (userInfo.token) {
            token.value = userInfo.token
        }
        if (userInfo.username) {
            username.value = userInfo.username
        }
    }

    // 登录方法
    const loginAction = async (loginData: LoginRequestData): Promise<any> => {
        const result = await reqLogin(loginData)

        if (result.code === "200") {
            const userInfo = {
                token: result.data.token,
                username: result.data.username,
            }
            isHr.value = result.data.is_hr === 1

            // 更新状态和存储
            updateUserState(userInfo)
            saveUserToStorage(userInfo)

            // 登录成功后跳转
            router.push("/home")
            return result
        }
        throw new Error(result.msg || "登录失败")
    }

    // 退出登录
    const logout = () => {
        try {
            // 清除状态
            updateUserState({token: '', username: ''})
            // 清除存储
            clearUserFromStorage()
            // 跳转登录页
            router.push('/login')
            ElMessage.warning('已退出登录')
        } catch (error) {
            console.error('退出登录失败:', error)
            ElMessage.error('退出登录失败')
        }
    }

    // 检查是否已登录
    const isLoggedIn = computed(() => !!token.value)

    return {
        token,
        username,
        isLoggedIn,
        isHr,
        loginAction,
        logout
    }
}, {
    persist: true
})
